import { getUserProfileApi, loginApi } from "@/api/User";
import { setToken, getToken, removeToken } from "@/utils/auth";

//用户模块(登录 获取用户资料)
export default {
  namespaced: true, //开启命名空间
  state: {
    token: getToken() || "", //token
    userInfo: {},
  },

  mutations: {
    // 设置token
    setToken(state, token) {
      state.token = token;
      setToken(token);
    },
    // 设置用户资料
    setUserInfo(state, data) {
      state.userInfo = { ...data };
    },
    //清除token
    removeToken(state) {
      state.token = null;
      removeToken();
    },
  },
  actions: {
    // 登录操作
    async loginAction({ commit }, data) {
      const { token } = await loginApi(data);
      commit("setToken", token);
    },
    //获取用户资料的请求
    async getUserProfileAction({ commit }) {
      let res = await getUserProfileApi();
      commit("setUserInfo", res);
      return res;
    },
    //退出功能
    quitOut({ commit }) {
      //1.清除token
      commit("removeToken");
      // 2.清除用户资料
      commit("setUserInfo", {});
    },
  },
};
